package guijavacommander.tasks;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;

/**
 * User: Deady
 * Date: 16.07.2009
 * Time: 12:31:34
 */
public class RemoveFilesTask extends AbstractTask {
    private File[] srcFiles;
    private Log logger = LogFactory.getLog(RemoveFilesTask.class);
    private int fileCount = 0;
    private int filesRemoved = 0;

    public RemoveFilesTask(File[] srcFiles) {
        this.srcFiles = srcFiles;
        for (File f : srcFiles) {
            fileCount += getFileCount(f);
        }
    }

    private int getFileCount(File file) {
        int res = 1;
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                res+=getFileCount(child);
            }
        }
        return res;
    }



    public void execute() {
        for (File f : srcFiles) {
            removeFile(f);
        }
    }

    private void removeFile(File file) {
        logger.debug("Removing: "+file);
        fireDescriptionChanged("Removing "+file);
        if (file.isDirectory()) {
            for (File child : file.listFiles()) {
                removeFile(child);
            }
        }
        file.delete();
        filesRemoved++;
        fireProgressChanged(filesRemoved);
    }

    public int getMin() {
        return 0;
    }

    public int getMax() {
        return fileCount;
    }

    public String getDescription() {
        return "Deleting files";
    }
}
